package com.jt.www.common.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.jt.www.admin.order_pc.service.ApplicationFormService;
import com.jt.www.common.service.OpeLogService;
import com.jt.www.common.service.zqsign.dependency.EncryptData;
import com.jt.www.model.oplog.vo.InsureTrackVO;
import com.jt.www.model.remote.ins.InsManagerResultVO;
import com.jt.www.model.reps.GenericListResponse;
import com.jt.www.model.reps.GenericResponse;
import com.jt.www.model.reps.ResponseData;
import com.jt.www.model.vo.InsManagerQo;
import com.jt.www.remote.ESClient;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/*
 *  投保軌跡
 * @Author xq.wu
 * @Date 11:52 2019/11/1
 * @Param
 * @return
 **/
@Service
public class OpeLogServiceImpl implements OpeLogService {

    public static final Logger log = LoggerFactory.getLogger(OpeLogServiceImpl.class);
    private static final String INSURE_SERVICE = "edu_ins_trace";
    @Resource
    ESClient esClient;
    @Autowired
    private ApplicationFormService applicationFormService;

    /**
     * @Description: 投保轨迹查询接口
     * @Param: [insureTrackVO]
     * @return: org.springframework.http.ResponseEntity<?>
     * @Author: lxw
     * @Date: 2019/5/13
     */
    @Override
    public ResponseEntity<?> insureTrackCheck(InsureTrackVO insureTrackVO) {
        log.info("================投保轨迹查询开始=================");
        try {
            String appCode = insureTrackVO.getAppCode();
            String insuranceNo = insureTrackVO.getInsuranceNo();
            String insured = insureTrackVO.getInsuredName();
            String dc = insureTrackVO.getDc();
            String cc = insureTrackVO.getCc();
            String opType = "";
            String opName = "";
            String opNode = "";
            String sysCode = "";
            String uc = "";
            String un = "";
            String sql = "cc = " + "\"" + cc + "\"";

            if (appCode != null && !"".equals(appCode)) {
                ResponseData applicationList = getApplicationForm(appCode, insureTrackVO);
                //投保中心返回的结果集
                List<InsManagerResultVO> insManagerResultVO = (List<InsManagerResultVO>) applicationList.getList();
                insManagerResultVO = JSON.parseArray(JSON.toJSONString(insManagerResultVO), InsManagerResultVO.class);

                if (insManagerResultVO.size() > 0) {
                    //获取到该投保单的产品编码
                    String productCode = insManagerResultVO.get(0).getProductCode();
                    if (dc != null && !"".equals(dc)) {
                        if (!dc.equals(productCode)) {
                            return GenericListResponse.listAndCount(Lists.newArrayList(), 0L);
                        }
                    } else {
                        sql = sql + "and dc = " + "\"" + appCode + "\"";
                    }
                }
            } else {
                if (dc != null && !"".equals(dc)) {
                    sql += "and dc = " + "\"" + dc + "\"";
                }
            }

            //如果投保单号为空,保单号有值，根据保单号反查投保单号，调用es去查询
            if ((insuranceNo != null && !"".equals(insuranceNo)) && StringUtils.isBlank(appCode)) {
                //根据保单号查询到投保单号
                ResponseData applicationList = getApplicationForm(appCode, insureTrackVO);
                //投保中心返回的结果集
                List<InsManagerResultVO> insManagerResultVO = (List<InsManagerResultVO>) applicationList.getList();
                insManagerResultVO = JSON.parseArray(JSON.toJSONString(insManagerResultVO), InsManagerResultVO.class);

                if (insManagerResultVO.size() > 0) {
                    appCode = insManagerResultVO.get(0).getAppCode();
                    sql = sql + "and dc = " + "\"" + appCode + "\"";
                }

            }


            //根据输入的被保险人去查询
            if ((insured != null && !"".equals(insured)) && StringUtils.isBlank(dc) && StringUtils.isBlank(appCode)) {
                //根据保单号查询到投保单号
                ResponseData applicationList = getApplicationForm(appCode, insureTrackVO);
                if (applicationList.getList() != null && applicationList.getList().size() > 0) {
                    //投保中心返回的结果集
                    List<InsManagerResultVO> insManagerResultVO = (List<InsManagerResultVO>) applicationList.getList();
                    insManagerResultVO = JSON.parseArray(JSON.toJSONString(insManagerResultVO), InsManagerResultVO.class);

                    List<String> appCodeList = new ArrayList<>();
                    if (insManagerResultVO.size() > 0) {
                        StringBuffer dcSql = new StringBuffer("and dc in (");
                        for (InsManagerResultVO insManagerResultVO1 : insManagerResultVO) {
                            appCodeList.add(insManagerResultVO1.getAppCode());
                            dcSql.append("\"").append(insManagerResultVO1.getAppCode()).append("\"").append(",");
                        }
                        sql = sql + dcSql.toString().substring(0, dcSql.length() - 1) + ")";
                    }
                } else {
                    return GenericListResponse.listAndCount(Lists.newArrayList(), 0L);
                }

            }

            if (insureTrackVO.getSysCode() != null && !"".equals(insureTrackVO.getSysCode())) {
                sysCode = insureTrackVO.getSysCode();
                sql = sql + "and sysCode = " + "\"" + sysCode + "\"";
            }
            if (insureTrackVO.getOpType() != null && !"".equals(insureTrackVO.getOpType())) {
                opType = insureTrackVO.getOpType();
                sql = sql + "and opType = " + "\"" + opType + "\"";
            }
            if (insureTrackVO.getOpName() != null && !"".equals(insureTrackVO.getOpName())) {
                opName = insureTrackVO.getOpName();
                sql = sql + "and opName = " + "\"" + opName + "\"";
            }
            if (insureTrackVO.getOpNode() != null && !"".equals(insureTrackVO.getOpNode())) {
                opNode = insureTrackVO.getOpNode();
                sql = sql + "and opNode = " + "\"" + opNode + "\"";
            }
            if (insureTrackVO.getUc() != null && !"".equals(insureTrackVO.getUc())) {
                uc = insureTrackVO.getUc();
                sql = sql + "and uc = " + "\"" + uc + "\"";
            }
            if (insureTrackVO.getUn() != null && !"".equals(insureTrackVO.getUn())) {
                un = insureTrackVO.getUn();
                sql = sql + "and un = " + "\"" + un + "\"";
            }


            if (insureTrackVO.getStartTime() != null && !"".equals(insureTrackVO.getStartTime())) {
                String time = insureTrackVO.getStartTime();
                sql = sql + "and createTime > " + "\"" + time + "\"";
            }

            if (insureTrackVO.getEndTime() != null && !"".equals(insureTrackVO.getEndTime())) {
                String endTime = insureTrackVO.getEndTime();
                sql = sql + "and createTime < " + "\"" + endTime + "\"";
            }


            log.info("====投保轨迹查询入参=====>>" + sql);
            //service ？
            ResponseEntity<GenericListResponse> responseEntity = esClient.searchLogV2(INSURE_SERVICE,
                    null, null, null, null, null, EncryptData.encode(sql), insureTrackVO.getPn(), insureTrackVO.getPs(), "@timestamp", "desc", true, null);
            log.info("====投保轨迹查询返回=====>>" + responseEntity);
            GenericListResponse response = responseEntity.getBody();

            if (response.getCode().equals(GenericResponse.CODE_NG)) {
                return GenericListResponse.ng(response.getMsg());
            }
            //获取到es查询出来的数据,进行过滤处理
            if ((appCode != null && !"".equals(appCode)) || (insuranceNo != null && !"".equals(insuranceNo))) {
                List<InsureTrackVO> insureTrackVOS = JSONObject.parseArray(JSONObject.toJSONString(response.getList())).toJavaList(InsureTrackVO.class);
                for (InsureTrackVO insureTrackVOS1 : insureTrackVOS) {
                    //根据查询出来的列表再去查询es，获取到最近一条的所以操作记录
                    String opIp = insureTrackVOS1.getOpIp();
                    String userCode = insureTrackVOS1.getUc();
                    //获取到当前投保单查询出来的时间
                    String createDate = insureTrackVOS1.getCreateTime();
                    //根据查询出来的时间搜索当天的轨迹
                    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String newStartTime = "";
                    try {
                        long dif = df.parse(createDate).getTime() - 86400 * 1000;//减一天
                        Date date = new Date();
                        date.setTime(dif);
                        newStartTime = df.format(date);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    String newSql = "cc = " + "\"" + cc + "\"" + "and opIp = " + "\"" + opIp + "\"" + "and createTime < " + "\"" + createDate + "\"" + "and createTime > " + "\"" + newStartTime + "\""
                            + "and uc = " + "\"" + userCode + "\"";
                    if (insureTrackVO.getOpType() != null && !"".equals(insureTrackVO.getOpType())) {
                        opType = insureTrackVO.getOpType();
                        newSql = newSql + "and opType = " + "\"" + opType + "\"";
                    }
                    if (insureTrackVO.getOpName() != null && !"".equals(insureTrackVO.getOpName())) {
                        opName = insureTrackVO.getOpName();
                        newSql = newSql + "and opName = " + "\"" + opName + "\"";
                    }
                    if (insureTrackVO.getOpNode() != null && !"".equals(insureTrackVO.getOpNode())) {
                        opNode = insureTrackVO.getOpNode();
                        newSql = newSql + "and opNode = " + "\"" + opNode + "\"";
                    }
                    if (insureTrackVO.getUn() != null && !"".equals(insureTrackVO.getUn())) {
                        un = insureTrackVO.getUn();
                        newSql = newSql + "and un = " + "\"" + un + "\"";
                    }

                    if ((appCode != null && !"".equals(appCode)) && (opNode != null && !"".equals(opNode))) {
                        newSql = newSql + "and dc = " + "\"" + appCode + "\"";
                    }

                    if (insureTrackVO.getSysCode() != null && !"".equals(insureTrackVO.getSysCode())) {
                        sysCode = insureTrackVO.getSysCode();
                        newSql = newSql + "and sysCode = " + "\"" + sysCode + "\"";
                    }
                    if (insureTrackVO.getStartTime() != null && !"".equals(insureTrackVO.getStartTime())) {
                        String time = insureTrackVO.getStartTime();
                        newSql = newSql + "and createTime > " + "\"" + time + "\"";
                    }

                    if (insureTrackVO.getEndTime() != null && !"".equals(insureTrackVO.getEndTime())) {
                        String endTime = insureTrackVO.getEndTime();
                        newSql = newSql + "and createTime < " + "\"" + endTime + "\"";
                    }


                    log.info("====投保轨迹第二次查询入参Sql=====>>" + newSql);
                    //service ？
                    responseEntity = esClient.searchLogV2(INSURE_SERVICE,
                            null, null, null, null, null, EncryptData.encode(newSql), insureTrackVO.getPn(), insureTrackVO.getPs(), "@timestamp", "desc", true, null);
                    log.info("====投保轨迹第二次查询返回=====>>" + responseEntity);
                    response = responseEntity.getBody();
                    // 根据时间进行排序
                    List<InsureTrackVO> newInsureTrackVOS = JSONObject.parseArray(JSONObject.toJSONString(response.getList())).toJavaList(InsureTrackVO.class);
                    Collections.sort(newInsureTrackVOS, new Comparator<InsureTrackVO>() {
                        public int compare(InsureTrackVO o1, InsureTrackVO o2) {
                            return o1.getCreateTime().compareTo(o2.getCreateTime());
                        }
                    });
                    return GenericListResponse.listAndCount(newInsureTrackVOS, response.getTotal());

                }
            }
            List<InsureTrackVO> insureTrackVOS = JSONObject.parseArray(JSONObject.toJSONString(response.getList())).toJavaList(InsureTrackVO.class);
            return GenericListResponse.listAndCount(insureTrackVOS, response.getTotal());
        } catch (Exception e) {
            String mg = e.getMessage();
            return GenericListResponse.ng(mg);
        }
    }

    /*
     *  根据前端传进来的属性,远程查询投保具体信息
     * @Author xq.wu
     * @Date 16:15 2019/11/7
     * @Param [appCode, insureTrackVO]
     * @return org.springframework.http.ResponseEntity<com.jt.www.model.reps.GenericListResponse<com.jt.www.model.remote.ins.InsManagerResultVO>>
     **/
    public ResponseData getApplicationForm(String appCode, InsureTrackVO insureTrackVO) {
        String findCode = "EDU_" + System.currentTimeMillis();
        InsManagerQo insManagerQo = new InsManagerQo();
        insManagerQo.setAppCode(appCode);
        insManagerQo.setUserCode(insureTrackVO.getUserCode());
        insManagerQo.setChannelCode("edu");
        insManagerQo.setInsuredName(insureTrackVO.getInsuredName());
        insManagerQo.setPolicyNo(insureTrackVO.getInsuranceNo());
        insManagerQo.setChannelType(insureTrackVO.getChannelType());
        insManagerQo.setLevel(insureTrackVO.getLevel());
        ResponseData applicationList = null;
        try {
            applicationList = applicationFormService.findApplicationForm(insManagerQo, findCode, false);
            log.error("远程调用投保单查询失败，请稍后重试");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return applicationList;
    }


}
